/* $Id: GradientPanel.java,v 1.5 2007/09/07 06:51:21 gigabass Exp $
 *
 * Copyright (c) Guido Ludwig. All rights reserved.
 * Use is subject to license terms.
 */

package de.guidoludwig.af;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.LayoutManager;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 * @author Guido
 * 
 */
public class GradientPanel extends JPanel {

//	public static JPanel createHorizontalMirroredGP(LayoutManager manager,
//			Color startColor, Color endColor) {
//		return new GradientPanel(manager, startColor,endColor);
//	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Start Color for the Gradient
	 */
	private Color startColor;

	/**
	 * End Color for the Gradient
	 */
	private Color endColor;

	/**
	 * Percentage of width where the gradient is mirrored ( as value from 0 to
	 * 1) Default is 0.5
	 */
	private double mirrorX;

	

	private boolean horizontal;

	public GradientPanel(Color start, Color end) {
		this(new FlowLayout(), start, end);
	}

	public GradientPanel(LayoutManager manager, Color start, Color end) {
		super(manager);
//		startColor = start;
//		endColor = end;
		startColor = getBackground();
		endColor = startColor.darker();
		setOpaque(false);
		mirrorX = 0.5;
		horizontal = false;
	}
	
	
	@Override
	public void paint(Graphics g) {
		Graphics2D g2d = (Graphics2D) g;
		if (horizontal) {
			paintHorizontal(g2d);
		} else {
			paintVertical(g2d);
		}
		super.paint(g);
	}
	
	private void paintHorizontal(Graphics2D g2d) {
		int mirrorWidth = (int)(mirrorX * getWidth());
		GradientPaint gradient = new GradientPaint(0, 0, startColor,
				mirrorWidth, 0, endColor);
		g2d.setPaint(gradient);
		g2d.fillRect(0, 0, mirrorWidth, getHeight());
		
		gradient = new GradientPaint(mirrorWidth, 0, endColor,
				getWidth(), 0, startColor);
		g2d.setPaint(gradient);
		g2d.fillRect(mirrorWidth , 0, getWidth(), getHeight());
	}
	
	private void paintVertical(Graphics2D g2d) {
		int mirrorWidth = (int)(mirrorX * getHeight());
		GradientPaint gradient = new GradientPaint(0, 0, startColor,
				0,mirrorWidth, endColor);
		g2d.setPaint(gradient);
		g2d.fillRect(0, 0, getWidth(),  mirrorWidth);
		
		gradient = new GradientPaint(0, mirrorWidth, endColor,
				0, getHeight(), startColor);
		g2d.setPaint(gradient);
		g2d.fillRect(0 , mirrorWidth, getWidth(), getHeight());
	}	

	public static void main(String[] args) {
		JPanel panel = new GradientPanel(Color.BLUE, Color.RED);
		panel.setPreferredSize(new Dimension(100, 100));
		JLabel label = new JLabel("Hello");
		label.setOpaque(false);
		panel.add(label);
		JFrame frame = new JFrame();
		frame.getContentPane().add(panel);
		frame.pack();
		frame.setVisible(true);
	}
}
